<template>
    <div>
       <!--面包屑导航区-->
       <el-breadcrumb separator-class="el-icon-arrow-right">
           <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
           <el-breadcrumb-item>权限管理</el-breadcrumb-item>
           <el-breadcrumb-item>角色列表</el-breadcrumb-item>
       </el-breadcrumb>
          <!--卡片视图-->
        <el-card>
           <el-button type="primary" @click="addRoleDialog">添加角色</el-button>
           <el-table :data="roleslist" border stripe>
            <!--展开列-->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row v-for="(item1,i1) in scope.row.children" 
                     :class="['bdbottom',i1===0?'bdtop':'','vcenter']" :key="item1.id">
                      <!--渲染一级权限-->
                      <el-col :span="6">
                        <el-tag closable @close="removeRightById(scope.row,item1.id)">{{ item1.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!--渲染二和三级权限-->
                      <el-col :span="18">
                        <!--通过for循环嵌套渲染二级权限-->
                         <el-row  :class="[i2 === 0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                            <el-col :span="6">
                                <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success" >{{ item2.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>   
                            </el-col>
                            <el-col :span="18">
                                <el-tag closable @close="removeRightById(scope.row,item3.id)"  v-for="(item3,i3) in item2.children" :key="item3.id" type="warning">{{ item3.authName}}</el-tag>         
                            </el-col>
                        </el-row>
                      </el-col>
                    </el-row>      
                </template>
              </el-table-column>
            <!--索引行-->
               <el-table-column type="index" prop="序号" width="120px">
               </el-table-column>
               <el-table-column prop="roleName" label="角色名称">
               </el-table-column> 
               <el-table-column prop="roleDesc" label="角色描述">
               </el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                   <!--修改按钮-->
                   <el-button type="primary" icon="el-icon-edit" size="small" @click="showRoleEditDialog(scope.row)">编辑</el-button>
                   <!--删除按钮-->
                   <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRole(scope.row.id)">删除</el-button>
                   <!--分配角色按钮-->
                   <el-tooltip effect="dark" content="分配角色" placement="top">
                     <el-button type="warning" 
                     icon="el-icon-setting"
                     @click="showSetRightDialog(scope.row)">分配权限</el-button>
                   </el-tooltip> 
                </template>
            </el-table-column>
           </el-table>
       </el-card>  
        <!--增加角色对话框-->
    <el-dialog
        title="增加角色"
        :visible.sync="addRoleDialogVisible"
        width="36%"
        @close="addroleDialogClosed">
        <el-form :model="addRoleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
     </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleDialogVisible= false">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
       <!--分配权限对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="36%"
        @close="setRightDialogClosed">
        <!--树形控件-->
      <el-tree :data="rightslist" :props="treeProps"
      show-checkbox node-key="id" default-expand-all
      :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
      <!--修改角色信息的对话框-->  
    <el-dialog
        title="修改角色信息" 
        :visible.sync="editRoleDialogVisible" 
        width="30%"
        @close="editRoleDialogClosed"
        >
      <!--内容主体区-->  
        <el-form :model="editRoleForm" label-width="100px">
            <el-form-item label="id">
                <el-input v-model="editRoleForm.id" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editRoleForm.roleDesc"></el-input>
            </el-form-item>
     </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
    </el-dialog> 
    </div>
   </template>
   
   <script>
   export default{
    data() {
     return {
        //所有角色列表数据
        roleslist:[],
        //控制分配角色权限的对话框
        setRightDialogVisible:false,
        //所有权限的数据
        rightslist:[],
        //树形控件的属性绑定对象
        treeProps:{
          label:'authName',
          children:'children'
        },
        //默认选中的节点Id数值
        defKeys:[],
        roleId:0,
        addRoleDialogVisible:false,
        addRoleForm:{
          roleName:'',
          roleDesc:''
        },
        editRoleForm:{},
        editRoleDialogVisible:false
     }
    },
    created(){
       this.getRolesList()
       },
    methods: {
      async getRolesList(){
       const {data:res} = await this.$http.get(`roles`)
        if(res.meta.status!==200)return this.$message.error('获取权限列表失败')
        this.roleslist=res.data 
       },
       //根据id删除对应的权限，
       async removeRightById(role,rightId){
        //弹框提示是否要删除
        const confirmResult=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err) 
          if(confirmResult!=='confirm'){
            return this.$message.info('已取消删除')
          }
          const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
          if(res.meta.status!==200){
            return this.$message.error('删除失败')
          }
          role.children=res.data
       },
        //展示分配权限的对话框
       async showSetRightDialog(role){    
          //获取所有权限的数据
          const {data:res}=await this.$http.get('rights/tree')
          if(res.meta.status!=200){
            return this.$message.error("获取权限数据失败")
          }
          //把获取到的权限数据保存到list中
          this.rightslist=res.data
          console.log(res.data)
          this.roleId=role.id
          //递归获取三级节点的ID
          this.getLeafKeys(role,this.defKeys)
          this.setRightDialogVisible=true
       },
       //通过递归的形式，获取角色下所有三级权限的ID，并保存到defKeys数组中
       getLeafKeys(node,arr){
        //如果当前node节点不包含children属性，则是三级节点
          if(!node.children){
            return arr.push(node.id)
          }
          node.children.forEach(item=>
          this.getLeafKeys(item,arr))
       },
       //监听分配权限对话框的关闭事件
       setRightDialogClosed(){
          this.defKeys=[]
       },
       //点击为角色分配权限
      async allotRights(){
          const keys=[
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys(),
          ]
          const idStr=keys.join(',')
          const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
          if(res.meta.status!==200) return this.$message.error('分配权限失败')
          this.setRightDialogVisible=false
          this.getRolesList()
          return this.$message.success('分配权限成功')
       },
       //添加角色列表对话框
       addRoleDialog(){
        this.addRoleDialogVisible=true
       },
       //点击确认添加用户
       async addRole(){
        const {data:res} = await this.$http.post('roles',this.addRoleForm)
            if(res.meta.status!==201) {
                this.$message.error('添加用户失败')}
            this.$message.success('添加用户成功') 
            //隐藏添加用户的对话框
            this.addRoleDialogVisible=false
            //重新获取用户列表数据
            this.getRolesList()
       },
       //关闭后清空数据
       addroleDialogClosed(){
        this.addRoleForm={
          roleName:'',
          roleDesc:''
        }
       },
      showRoleEditDialog(role){ 
      this.editRoleForm=role
      this.editRoleDialogVisible=true;
    },
    async editRole(){
      const {data:res} = await this.$http.put('roles/'+this.editRoleForm.id,
            {roleName:this.editRoleForm.roleName,
             roleDesc:this.editRoleForm.roleDesc})
      if(res.meta.status!==200)  return this.$message.error('修改失败')
      this.getRolesList(),
      this.editRoleDialogVisible=false;

    },
    editRoleDialogClosed(){
      this.editRoleForm={}
    },
    async deleteRole(id){
      const {data:res}=await this.$http.delete(`roles/${id}`)
      if(res.meta.status!==200)  return this.$message.error('删除失败')
      this.getRolesList()
      this.$message.success('成功删除')
    }
      }
   } 
   </script>
   
   <style lang="less" scoped>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .bdtop{
    border-top:1px solid #eee;
  }
  .bdbottom{
      border-bottom: 1px solid #eee;
  }
  .el-tag{
      margin: 8px;
      font-size:16px;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }

   </style>